// src/store/modules/chatList.js
import service from "../../utils/request";

const state = {
  // 聊天列表
  list: [],
  // 当前选中的聊天
  currentId: null,
  // 未读消息数量
  unreadCounts: {},
  // 搜索关键词
  searchKeyword: "",
  // 置顶聊天
  pinnedChats: [],
  // 免打扰设置
  muteSettings: {},
  // 隐藏聊天
  hiddenChats: [],
  // 排序设置
  sortBy: "latestTime", // latestTime, name, unreadCount
  sortOrder: "desc", // asc, desc
  // 过滤设置
  filterType: "all", // all, unread, pinned, muted, hidden
  // 加载状态
  loading: false,
};

const mutations = {
  // 基础操作
  SET_LIST(state, list) {
    state.list = list;
  },

  // 加载状态
  SET_LOADING(state, loading) {
    state.loading = loading;
  },

  UPDATE_CHAT(state, { id, updates }) {
    const index = state.list.findIndex((chat) => chat.id === id);
    if (index !== -1) {
      state.list[index] = { ...state.list[index], ...updates };
    }
  },

  REMOVE_CHAT(state, id) {
    state.list = state.list.filter((chat) => chat.id !== id);
    // 清理相关设置
    state.pinnedChats = state.pinnedChats.filter((chatId) => chatId !== id);
    state.hiddenChats = state.hiddenChats.filter((chatId) => chatId !== id);
    delete state.unreadCounts[id];
    delete state.muteSettings[id];
  },

  SET_CURRENT(state, id) {
    state.currentId = id;
  },

  SET_UNREAD_COUNT(state, { id, count }) {
    state.unreadCounts[id] = count;
  },

  SET_SEARCH_KEYWORD(state, keyword) {
    state.searchKeyword = keyword;
  },

  // 置顶操作
  PIN_CHAT(state, id) {
    if (!state.pinnedChats.includes(id)) {
      state.pinnedChats.push(id);
    }
  },

  UNPIN_CHAT(state, id) {
    state.pinnedChats = state.pinnedChats.filter((chatId) => chatId !== id);
  },

  // 免打扰操作
  MUTE_CHAT(state, { id, muteUntil }) {
    state.muteSettings[id] = {
      isMuted: true,
      muteUntil: muteUntil || null,
      muteTime: Date.now(),
    };
  },

  UNMUTE_CHAT(state, id) {
    delete state.muteSettings[id];
  },

  // 隐藏操作
  HIDE_CHAT(state, id) {
    if (!state.hiddenChats.includes(id)) {
      state.hiddenChats.push(id);
    }
  },

  SHOW_CHAT(state, id) {
    state.hiddenChats = state.hiddenChats.filter((chatId) => chatId !== id);
  },

  // 排序设置
  SET_SORT_BY(state, sortBy) {
    state.sortBy = sortBy;
  },

  SET_SORT_ORDER(state, order) {
    state.sortOrder = order;
  },

  // 过滤设置
  SET_FILTER_TYPE(state, type) {
    state.filterType = type;
  },

  // 更新聊天的最新消息
  UPDATE_LATEST_MESSAGE(state, { chatId, message, messageType = 'text' }) {
    const chat = state.list.find(chat => chat.id === chatId);
    if (chat) {
      chat.latestMessage = message;
      chat.latestMessageType = messageType;
      chat.latestTime = new Date().toISOString();
      
      // 如果是自己发送的消息，不增加未读数量
      if (message.isMyselfMsg) {
        // 自己发送的消息，未读数量保持为0
        state.unreadCounts[chatId] = 0;
      }
    }
  },

  // 更新聊天的最新消息（用于接收消息）
  UPDATE_LATEST_MESSAGE_RECEIVED(state, { chatId, message, messageType = 'text' }) {
    const chat = state.list.find(chat => chat.id === chatId);
    if (chat) {
      chat.latestMessage = message;
      chat.latestMessageType = messageType;
      chat.latestTime = new Date().toISOString();
      
      // 接收到的消息，增加未读数量
      if (!message.isMyselfMsg) {
        state.unreadCounts[chatId] = (state.unreadCounts[chatId] || 0) + 1;
      }
    }
  },

  // 更新星标状态
  UPDATE_STAR_STATUS(state, { chatId, isStar }) {
    const chat = state.list.find(chat => chat.id === chatId);
    if (chat) {
      chat.isStar = isStar;
    }
  },

  // 添加聊天到列表
  ADD_CHAT(state, chatData) {
    // 检查是否已存在（通过id或friendId检查）
    const existingChat = state.list.find(chat => 
      chat.id === chatData.id || 
      chat.friendId === chatData.friendId ||
      chat.targetId === chatData.targetId
    );
    if (!existingChat) {
      state.list.unshift(chatData);
    }
  },

  // 更新备注
  UPDATE_REMARK(state, { chatId, remark }) {
    const chat = state.list.find(chat => chat.id === chatId);
    if (chat) {
      chat.remark = remark;
      chat.displayName = remark; // 更新显示名称
    }
  },
};

const actions = {
  // 获取聊天列表（兼容旧接口）
  async fetchChatList({ commit }, { keyword = '' } = {}) {
    try {
      // 检查缓存
      const cachedData = localStorage.getItem("chatList_cache");
      if (cachedData) {
        const { data, timestamp } = JSON.parse(cachedData);
        // 检查缓存是否过期（5分钟）
        if (Date.now() - timestamp < 5 * 60 * 1000) {
          commit("SET_LIST", data);
          return data;
        }
      }
      // 从服务器加载
      const res = await service({
        method: "get",
        url: `/chat/list?keyword=${keyword}`,
      });
      // 处理响应数据
      const chatList = res.data || [];
      commit("SET_LIST", chatList);
      // 缓存数据
      localStorage.setItem(
        "chatList_cache",
        JSON.stringify({
          data: chatList,
          timestamp: Date.now(),
        })
      );
      return chatList;
    } catch (error) {
      console.error("chatList 获取失败:", error);
      // 尝试使用缓存数据
      const cachedData = localStorage.getItem("chatList_cache");
      if (cachedData) {
        const { data } = JSON.parse(cachedData);
        commit("SET_LIST", data);
        console.warn("chatList 使用缓存数据");
        return data;
      } else {
        // 使用空数组作为默认值
        commit("SET_LIST", []);
        console.warn("chatList 使用默认空数据");
        return [];
      }
    }
  },

  // 初始化聊天列表模块
  async initialize({ commit, state }) {
    // 防止重复初始化
    if (state.loading) {
      console.log("chatList 正在加载中，跳过重复初始化");
      return;
    }
    
    commit("SET_LOADING", true);
    
    try {
      // 检查缓存
      const cachedData = localStorage.getItem("chatList_cache");
      if (cachedData) {
        const { data, timestamp } = JSON.parse(cachedData);
        // 检查缓存是否过期（5分钟）
        if (Date.now() - timestamp < 5 * 60 * 1000) {
          commit("SET_LIST", data);
          console.log("chatList 使用缓存数据");
          return;
        } else {
          console.log("chatList 缓存已过期，重新加载");
        }
      }
      
      // 从服务器加载
      console.log("chatList 从服务器加载数据");
      const res = await service({
        method: "get",
        url: "/chat/list?keyword=",
      });
      
      // 处理响应数据
      const chatList = res.data || [];
      commit("SET_LIST", chatList);
      
      // 缓存数据
      localStorage.setItem(
        "chatList_cache",
        JSON.stringify({
          data: chatList,
          timestamp: Date.now(),
        })
      );
      console.log("chatList 数据加载完成，已缓存");

    } catch (error) {
      console.error("chatList 模块初始化失败:", error);
      // 尝试使用缓存数据
      const cachedData = localStorage.getItem("chatList_cache");
      if (cachedData) {
        try {
          const { data } = JSON.parse(cachedData);
          commit("SET_LIST", data);
          console.warn("chatList 使用缓存数据作为备用");
        } catch (parseError) {
          console.error("chatList 缓存数据解析失败:", parseError);
          commit("SET_LIST", []);
        }
      } else {
        // 使用空数组作为默认值
        commit("SET_LIST", []);
        console.warn("chatList 使用默认空数据");
      }
    } finally {
      // 确保加载状态被重置
      commit("SET_LOADING", false);
      console.log("chatList 加载状态已重置");
    }
  },
  // 加载聊天列表（保持向后兼容）
  async loadList({ dispatch }) {
    return dispatch("initialize");
  },

  // 检查聊天是否存在
  checkChatExists({ state }, chatData) {
    return state.list.find((chat) => {
      if (chatData.type === 0) {
        // 群聊：检查群ID
        return chat.type === 0 && chat.groupId === chatData.groupId;
      } else if (chatData.type === 1) {
        // 私聊：检查好友ID
        return chat.type === 1 && chat.friendId === chatData.friendId;
      }
      return false;
    });
  },

  // 获取或创建聊天
  async getOrCreateChat({ dispatch, state }, chatData) {
    const existingChat = state.list.find((chat) => {
      if (chatData.type === 0) {
        return chat.type === 0 && chat.groupId === chatData.groupId;
      } else if (chatData.type === 1) {
        return chat.type === 1 && chat.friendId === chatData.friendId;
      }
      return false;
    });

    if (existingChat) {
      return existingChat;
    }

    return await dispatch("createChat", chatData);
  },

  async createChat({ commit, state }, chatData) {
    try {
      // 检查是否已存在相同的聊天
      const existingChat = state.list.find((chat) => {
        // 根据聊天类型判断
        if (chatData.type === 0) {
          // 群聊：检查群ID
          return chat.type === 0 && chat.groupId === chatData.groupId;
        } else if (chatData.type === 1) {
          // 私聊：检查好友ID
          return chat.type === 1 && chat.friendId === chatData.friendId;
        }
        return false;
      });

      if (existingChat) {
        // 设置为当前聊天
        commit("SET_CURRENT", existingChat.id);
        return existingChat;
      }

      // 这里需要您提供对应的API
      // const newChat = await api.createChat(chatData)
      // commit('ADD_CHAT', newChat)
      // return newChat

      // 临时实现
      const newChat = {
        id: Date.now(),
        ...chatData,
        createdAt: new Date().toISOString(),
        latestTime: new Date().toISOString(),
        unreadCount: 0,
      };

      commit("ADD_CHAT", newChat);
      commit("SET_CURRENT", newChat.id);

      return newChat;
    } catch (error) {
      console.error("创建聊天失败:", error);
      throw error;
    }
  },

  async deleteChat({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.deleteChat(id)
      commit("REMOVE_CHAT", id);
    } catch (error) {
      console.error("删除聊天失败:", error);
    }
  },

  // 更新聊天的最新消息（发送消息时调用）
  updateLatestMessage({ commit }, { chatId, message, messageType = 'text' }) {
    commit("UPDATE_LATEST_MESSAGE", { chatId, message, messageType });
  },

  // 更新聊天的最新消息（接收消息时调用）
  updateLatestMessageReceived({ commit }, { chatId, message, messageType = 'text' }) {
    commit("UPDATE_LATEST_MESSAGE_RECEIVED", { chatId, message, messageType });
  },

  // 更新星标状态
  updateStarStatus({ commit }, { chatId, isStar }) {
    commit("UPDATE_STAR_STATUS", { chatId, isStar });
  },

  // 添加聊天到列表
  addChat({ commit }, chatData) {
    commit("ADD_CHAT", chatData);
  },

  // 更新备注
  updateRemark({ commit }, { chatId, remark }) {
    commit("UPDATE_REMARK", { chatId, remark });
  },

  // 清除未读消息数量
  clearUnreadCount({ commit }, chatId) {
    commit("SET_UNREAD_COUNT", { id: chatId, count: 0 });
  },

  // 增加未读消息数量
  addUnreadCount({ commit, state }, chatId) {
    const currentCount = state.unreadCounts[chatId] || 0;
    commit("SET_UNREAD_COUNT", { id: chatId, count: currentCount + 1 });
  },

  // 设置搜索状态
  setSearchStatus({ commit }, isSearching) {
    commit("SET_SEARCH_KEYWORD", isSearching ? "" : "");
  },

  // 搜索聊天
  searchChats({ commit, state }, keyword) {
    commit("SET_SEARCH_KEYWORD", keyword);
    // 返回过滤后的结果
    return state.list.filter(chat => 
      chat.name.toLowerCase().includes(keyword.toLowerCase())
    );
  },

  // 清除搜索
  clearSearch({ commit }) {
    commit("SET_SEARCH_KEYWORD", "");
  },

  // 置顶操作
  async pinChat({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.pinChat(id)
      commit("PIN_CHAT", id);
    } catch (error) {
      console.error("置顶聊天失败:", error);
    }
  },

  async unpinChat({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.unpinChat(id)
      commit("UNPIN_CHAT", id);
    } catch (error) {
      console.error("取消置顶失败:", error);
    }
  },

  // 免打扰操作
  async muteChat({ commit }, { id, muteUntil }) {
    try {
      // 这里需要您提供对应的API
      // await api.muteChat(id, muteUntil)
      commit("MUTE_CHAT", { id, muteUntil });
    } catch (error) {
      console.error("设置免打扰失败:", error);
    }
  },

  async unmuteChat({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.unmuteChat(id)
      commit("UNMUTE_CHAT", id);
    } catch (error) {
      console.error("取消免打扰失败:", error);
    }
  },

  // 隐藏操作
  async hideChat({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.hideChat(id)
      commit("HIDE_CHAT", id);
    } catch (error) {
      console.error("隐藏聊天失败:", error);
    }
  },

  async showChat({ commit }, id) {
    try {
      // 这里需要您提供对应的API
      // await api.showChat(id)
      commit("SHOW_CHAT", id);
    } catch (error) {
      console.error("显示聊天失败:", error);
    }
  },
};

const getters = {
  // 当前聊天
  currentChat: (state) => {
    return state.list.find((chat) => chat.id === state.currentId);
  },

  // 置顶聊天列表
  pinnedChats: (state) => {
    return state.list.filter((chat) => state.pinnedChats.includes(chat.id));
  },

  // 免打扰聊天列表
  mutedChats: (state) => {
    return state.list.filter((chat) => state.muteSettings[chat.id]?.isMuted);
  },

  // 隐藏聊天列表
  hiddenChats: (state) => {
    return state.list.filter((chat) => state.hiddenChats.includes(chat.id));
  },

  // 过滤后的聊天列表
  filteredList: (state) => {
    let list = state.list;

    // 按搜索关键词过滤
    if (state.searchKeyword) {
      const keyword = state.searchKeyword.toLowerCase();
      list = list.filter((chat) => chat.name.toLowerCase().includes(keyword));
    }

    // 按类型过滤
    switch (state.filterType) {
      case "unread":
        list = list.filter((chat) => (state.unreadCounts[chat.id] || 0) > 0);
        break;
      case "pinned":
        list = list.filter((chat) => state.pinnedChats.includes(chat.id));
        break;
      case "muted":
        list = list.filter((chat) => state.muteSettings[chat.id]?.isMuted);
        break;
      case "hidden":
        list = list.filter((chat) => state.hiddenChats.includes(chat.id));
        break;
    }

    // 排除隐藏的聊天（除非是查看隐藏列表）
    if (state.filterType !== "hidden") {
      list = list.filter((chat) => !state.hiddenChats.includes(chat.id));
    }

    // 排序
    list.sort((a, b) => {
      let aValue, bValue;

      switch (state.sortBy) {
        case "latestTime":
          aValue = a.latestTime || 0;
          bValue = b.latestTime || 0;
          break;
        case "name":
          aValue = a.name || "";
          bValue = b.name || "";
          break;
        case "unreadCount":
          aValue = state.unreadCounts[a.id] || 0;
          bValue = state.unreadCounts[b.id] || 0;
          break;
      }

      if (state.sortOrder === "asc") {
        return aValue > bValue ? 1 : -1;
      } else {
        return aValue < bValue ? 1 : -1;
      }
    });

    // 置顶聊天放在最前面
    const pinned = list.filter((chat) => state.pinnedChats.includes(chat.id));
    const unpinned = list.filter(
      (chat) => !state.pinnedChats.includes(chat.id)
    );

    return [...pinned, ...unpinned];
  },

  // 未读消息总数
  totalUnread: (state) => {
    return Object.values(state.unreadCounts).reduce(
      (total, count) => total + count,
      0
    );
  },

  // 免打扰状态
  isMuted: (state) => (id) => {
    const setting = state.muteSettings[id];
    if (!setting) return false;

    // 检查是否过期
    if (setting.muteUntil && Date.now() > setting.muteUntil) {
      return false;
    }

    return setting.isMuted;
  },

  // 置顶状态
  isPinned: (state) => (id) => {
    return state.pinnedChats.includes(id);
  },

  // 隐藏状态
  isHidden: (state) => (id) => {
    return state.hiddenChats.includes(id);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
